package cn.com.lms.business.exam.service;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.exam.persistence.entity.Question;

import cn.com.lms.business.exam.persistence.entity.QuestionVO;
import cn.com.lms.business.exam.persistence.repository.QuestionRepository;


import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.BaseService;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.util.BeanUtils;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class QuestionService extends BaseService<QuestionRepository, Question,Long> {


   public  Map findQuestionById(Long id){

        return  repository.findQuestionById(id);
    }

    public static QueryHelpBean getQueryHelpBean(String whereCoutSQL) {
        String selectSQL = "select eq.*,qc.category_name, (select count(1) from bnz_exam_question_subject qs where qs.question_id=eq.id and qs.is_delete=0) as  count," +
                "(select count(1) from bnz_exam_question_subject qs where qs.type=1 and qs.question_id=eq.id and qs.is_delete=0) as  single_count," +
                "(select count(1) from bnz_exam_question_subject qs where qs.type=2 and qs.question_id=eq.id and qs.is_delete=0) as  multiple_count," +
                "(select count(1) from bnz_exam_question_subject qs where qs.type=3 and qs.question_id=eq.id and qs.is_delete=0) as  judge_count," +
                "(select count(1) from bnz_exam_question_subject qs where qs.type=4 and qs.question_id=eq.id and qs.is_delete=0) as  fill_count," +
                "(select count(1) from bnz_exam_question_subject qs where qs.type=5 and qs.question_id=eq.id and qs.is_delete=0) as  explain_count";

        String whereSQL = " from bnz_exam_question as eq left join bnz_exam_question_category as qc on qc.id=eq.category_id where 1=1  "+ whereCoutSQL;
        QueryHelpBean queryBean = new QueryHelpBean(selectSQL + whereSQL, "select count(1)" + whereSQL, QuestionVO.class);
        return queryBean;
    }

    public Question updateQuestion(Question question){

        Optional<Question> questionOpt = findById(question.getId());
        if (!questionOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        Question target=questionOpt.get();
        BeanUtils.copyProperties(question,target);
        this.save(target);
        return  target;
    }

    /**
     * 查询所有题库
     * @return
     */
    public List<Map> queryQuestion(){
        return  repository.queryQuestion();
    }


    public Integer updateIsDelete(boolean isDelete, List<Long> id) {
        return repository.updateIsDelete(isDelete, id);
    }
}
